import 'dart:async';

import 'package:chathouse/model/client_order.dart';
import 'package:chathouse/pages/client/order/comment_order_page.dart';
import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../chat/chat_page.dart';
import '../../../constant/app_constant.dart';
import '../../../model/member_info.dart';
import '../../../public/event_bus.dart';
import 'all_order_dertail.dart';
import 'client_comment_detail_.dart';
import 'comment_detail.dart';

class ClientOrderList extends StatefulWidget {
  var type;

  ClientOrderList(this.type, {Key? key}) : super(key: key);

  @override
  State<ClientOrderList> createState() => _ClientOrderListState();
}

class _ClientOrderListState extends State<ClientOrderList>
    with NavigationHelper {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: true); // 刷新控件控制
  ClientOrder? clientOrder;

  MemberInfo? _memberInfo;

  StreamSubscription? refreshSubscription;

  @override
  void dispose() {
    refreshSubscription?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    // if (widget.type == null) {
    //   getAllOrderList();
    // } else {
    //   if (widget.type == 2) {
    //     getMembersComUser();
    //   } else {
    //     getProgressData();
    //   }
    // }

    getMembersInfo();
    refreshSubscription = eventBus.on<UpdateOrderListEvent>().listen((event) {
      pageNum = 1;
      rows.clear();
      if (widget.type == null) {
        getAllOrderList();
      } else {
        if (widget.type == 2) {
          getMembersComUser();
        } else {
          getProgressData();
        }
      }
    });
  }

  ///獲取個人信息
  getMembersInfo() {
    Apis.getMembersInfo().then((value) {
      Obj.dismissLoading();
      var jsonData = value?.data;
      _memberInfo = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);
      LogUtil.d("getMembersInfo success ");
      setState(() {});
      Obj.dismissLoading();
    }).catchError((error) {
      Obj.dismissLoading();
      LogUtil.d("getMembersInfo error");
    });
  }

  ///獲取全部訂單
  void getAllOrderList() {
    final para = {"pageNum": pageNum};
    Apis.getAllOrderList(para).then((value) {
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
      var json = value?.data;
      if (json == null) {
        return;
      }
      setState(() {
        clientOrder = ClientOrder.fromJson(json);
        rows.addAll(clientOrder?.rows ?? []);
      });
      if ((rows.length) >= (clientOrder?.total ?? 0)) {
        LogUtil.d("loadNoData loadNoData ${clientOrder?.total}");
        _refreshController.loadNoData();
        return;
      }
    }).catchError((error) {
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
    });
  }

  ///獲取進行中數據
  void getProgressData() {
    final params = {"acceptFlag": widget.type,"pageNum": pageNum};
    Apis.getOrderList(params).then((value) {
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
      var json = value?.data;
      if (json == null) {
        return;
      }
      setState(() {
        clientOrder = ClientOrder.fromJson(json);
      });
      rows.addAll(clientOrder?.rows ?? []);
      LogUtil.d("getOrderList successful ${clientOrder?.total}");
      if ((rows.length) >= (clientOrder?.total ?? 0)) {
        LogUtil.d("loadNoData loadNoData ${clientOrder?.total}");
        _refreshController.loadNoData();
        return;
      }
    }).catchError((error) {
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
      LogUtil.d("getOrderList error $error");
    });
  }

  List<Rows> rows = [];

  int pageNum = 1;

  ///獲取我的評語
  void getMembersComUser() {
    final params = {"pageNum": pageNum};
    Apis.getMembersComUser(params).then((value) {
      _refreshController.refreshCompleted();
      var json = value?.data;
      if (json == null) {
        return;
      }
      setState(() {
        clientOrder = ClientOrder.fromJson(json);
        rows.addAll(clientOrder?.rows ?? []);
      });
      if ((rows.length) >= (clientOrder?.total ?? 0)) {
        LogUtil.d("loadNoData loadNoData ${clientOrder?.total}");
        _refreshController.loadNoData();
        return;
      }
      LogUtil.d("membersComUser successful ${clientOrder?.total}");
    }).catchError((error) {
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
      LogUtil.d("getOrderList error $error");
    });
  }

  ///加載更多我的評語
  loadMoreMembersComUser() {
    if ((rows.length) >= (clientOrder?.total ?? 0)) {
      _refreshController.loadComplete();
      _refreshController.loadNoData();
      return;
    }
    pageNum += 1;

    if (widget.type == null) {
      getAllOrderList();
    } else if (widget.type == 1) {
      getProgressData();
    } else if (widget.type == 2) {
      getMembersComUser();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: () {
          loadMoreMembersComUser();
        },
        child: _getListView(),
      ),
    );
  }

  Widget _getEmptyWidget() {
    return Center(
        child: Text("沒有資料",
            style: getTextStyle(25.sp,
                color: MyColors.gary_139139139, fontType: FontType.BOLD)));
  }

  Widget _getListView() {
    if (clientOrder == null) {
      return _getEmptyWidget();
    }
    if (rows.isEmpty) {
      return _getEmptyWidget();
    }

    return ListView.separated(
      shrinkWrap: true,
      separatorBuilder: (BuildContext context, int index) {
        return Container(height: 0.2.w, color: MyColors.gary_112112112);
      },
      padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 12.w),
      itemCount: rows.length + 1,
      itemBuilder: (context, index) {
        if (index == rows.length) {
          return Container(height: 0.2.w, color: MyColors.gary_112112112);
        }
        return buildItem(index);
      },
    );
  }

  ///构建 item
  Widget buildItem(index) {
    Rows item = rows[index];
    double number = item.serviceEvaluation ?? 0;
    List stars = [];
    if (widget.type == 2) {
      for (int i = 0; i < number.ceil(); i++) {
        stars.add(i);
      }
    }
    return Container(
        padding: EdgeInsets.only(top: 28.w, bottom: 6.w),
        child: Column(children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ImageUtils.image(
                  widget.type == null || widget.type == 2
                      ? (rows[index].imagePath ?? "")
                      : rows[index].projectImg ?? "",
                  width: 80.w,
                  height: 80.w,
                  radius: 10.w,
                  imageType: ImageType.NETWORK,
                  fit: BoxFit.cover),
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(left: 16.w),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(rows[index].serviceName ?? "",
                            style: getTextStyle(20.sp,
                                color: Colors.black, fontType: FontType.BOLD)),
                        Row(
                          children: [
                            ImageUtils.image(
                                widget.type == null
                                    ? _memberInfo?.data?.memberImage ?? ""
                                    : rows[index].memberImage ?? "",
                                width: 28.w,
                                height: 28.w,
                                radius: 14.w,
                                imageType: ImageType.NETWORK,
                                fit: BoxFit.cover),
                            SizedBox(
                              width: 8.w,
                            ),
                            Text(
                                widget.type == null
                                    ? _memberInfo?.data?.membersName ?? ""
                                    : rows[index].membersName ?? "",
                                style: getTextStyle(16.sp,
                                    color: Colors.black,
                                    fontType: FontType.BOLD))
                          ],
                        ),
                        Visibility(
                          visible: widget.type == null &&
                              rows[index].numberOfPersonsQuoting != null &&
                              rows[index].newQuoting != null,
                          child: Text(
                                  "${(rows[index].newQuoting)}/${(rows[index].numberOfPersonsQuoting)}",
                                  style: getTextStyle(16.sp,
                                      color: Colors.black,
                                      fontType: FontType.BOLD))
                              .setContainer(margin: EdgeInsets.only(top: 18.w)),
                        )
                      ]),
                ),
              ),
              widget.type != 2
                  ? Text(
                      widget.type == null
                          ? (rows[index].projectStateStr() ?? "")
                          : rows[index].acceptFlagStr() ?? "",
                      style: getTextStyle(16.sp,
                          color: widget.type == null
                              ? (rows[index].allOrderStrColor())
                              : rows[index].acceptFlagStrColor(),
                          fontType: FontType.BOLD))
                  : Container(
                      height: 20,
                      margin: EdgeInsets.only(top: 4.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: List.generate(stars.length ?? 0, (index) {
                          return const Icon(Icons.star,
                              size: 16, color: Colors.redAccent);
                        }),
                      ),
                    ),
            ],
          ),
          Visibility(
            visible: (rows[index].evaluate ?? false) &&
                (rows[index].commented == false),
            child: Row(
              children: [
                const Spacer(),
                Center(
                  child: Text("撰寫評語",
                      style: getTextStyle(20.sp,
                          color: Colors.white, fontType: FontType.BOLD)),
                )
                    .setContainer(
                        width: 111.w,
                        height: 44.w,
                        decoration: BoxDecoration(
                            color: MyColors.green_99169104157608,
                            borderRadius: BorderRadius.circular(34.w)))
                    .setOnClickListener(() {
                  if (rows[index].commented ?? false) {
                    //跳轉去我的評語頁面
                    double number = rows[index].serviceEvaluation ?? 0;
                    var intNumber = number.toInt();
                    final map = {
                      "serviceEvaluation": intNumber,
                      "comUser": rows[index].comUser ?? ""
                    };
                    Get.to(ClientCommentDetailPage(map));
                    return;
                  }
                  navigateTo(CommentOrderPage(
                    rows[index].projectId ?? "",
                    isShowBottomBar: true,
                  ));

                  // Get.to(CommentOrderPage(
                  //     clientOrder?.rows?[index].projectId ?? ""));
                }, isInkWell: true)
              ],
            ),
          ),
        ])).setOnClickListener(() async {
      if (widget.type == null) {
        //全部
        Get.to(AllOrderDetailPage(rows[index].projectId.toString()));
        return;
      }

      if (widget.type == 2) {
        double number = item.serviceEvaluation ?? 0;
        var intNumber = number.toInt();
        final map = {
          "serviceName": item.serviceName,
          "membersName": item.membersName,
          "serviceEvaluation": intNumber,
          "comUser": item.comUser,
          "type": 1,
        };
        Get.to(CommentDetailPage(map));
        return;
      }

      final map = {
        "reviceuserId": rows[index].membersNo,
        "projectNo": rows[index].projectNo,
        "memberImage": rows[index].memberImage,
        "membersName": rows[index].membersName,
        "evaluate": rows[index].evaluate,
        "exhibition": rows[index].exhibition,
        "projectId": rows[index].projectId
      };
      LogUtil.d("map $map");
      var result = await Get.to(ChatPage(map));
      if (result) {
        _onRefresh();
      }
    }, isInkWell: true);
  }

  ///下拉刷新
  void _onRefresh() {
    pageNum = 1;
    rows.clear();
    if (widget.type == null) {
      getAllOrderList();
      return;
    }
    if (widget.type == 2) {
      getMembersComUser();
    } else {
      getProgressData();
    }
  }
}
